# -*-coding: Utf-8 -*-
# @File : api .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/10/7
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from FastapiTest.database.data_base import SessionLocal
from FastapiTest.schemas import schemas_base
from FastapiTest.models import models_base
from BloomFilter import BloomFilter
from RedisController import redis_connect

redis_conn = redis_connect.redis_conn
bloom_filter = BloomFilter(redis_conn)

# 创建子路由
views_api = APIRouter()


# 创建子依赖对象
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def base_response(code, msg, data=None):
    """基础返回格式"""
    if data is None:
        data = []
    result = {
        "code": code,
        "message": msg,
        "data": data
    }
    return result


def success(data=None, msg=''):
    """成功返回格式"""
    return base_response(200, msg, data)


def fail(code=-1, msg='', data=None):
    """失败返回格式"""
    return base_response(code, msg, data)


@views_api.post('/register')
async def register(data: schemas_base.CreateUser, db: Session = Depends(get_db)):
    """
    创建用户
    :param post: CreateUser
    :return:
    """
    # # 检查元素是否存在
    if bloom_filter.contains(data.dict().get('username')):
        return "用户名已被使用"
    db_user = models_base.User(**data.dict())
    # # 提交数据库
    db.add(db_user)
    # # 执行事务
    db.commit()
    # # 刷新数据
    db.refresh(db_user)

    # # 添加元素到布隆过滤器
    bloom_filter.add(data.dict().get('username'))

    if not db_user:
        return fail(msg=f"用户{data.username}创建失败!")

    return success(msg=f"用户{data.username}创建成功")


@views_api.post('/login')
async def login(data: schemas_base.Login, db: Session = Depends(get_db)):
    data = data.dict()
    username = data.get('username')
    password = data.get('password')
    print(username, password)
    user = db.query(models_base.User).filter(models_base.User.username == username,
                                             models_base.User.password == password).all()
    if user:
        return f" {username} 登陆成功"
    return f" {username} 登陆失败"
